package com.konsung.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.healthfile.R;
import com.konsung.kslibrary.base.BaseActivity;
import com.konsung.kslibrary.base.MvpView;
import com.konsung.presenter.ReportListPresenter;
import com.konsung.presenter.impl.ReportListPresenterImpl;
import com.konsung.ui.adapter.MeasureReportListAdapter;
import com.konsung.ui.adapter.PopupWindowAdapter;
import com.konsung.ui.defineview.ListPopupWindow;
import com.konsung.ui.defineview.LoadingDialog;
import com.konsung.ui.defineview.PopupDialog;
import com.konsung.util.BroadcastUtils;
import com.konsung.util.DBDataUtil;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.konsung.util.constant.GlobalConstant.IDCARD;

/**
 * Created by xiangshicheng on 2019/1/4 0004.
 * 用户体检报告列表页面
 */

public class ReportListActivity extends BaseActivity<ReportListPresenterImpl>
        implements ReportListPresenter.View, MvpView, CompoundButton.OnCheckedChangeListener
        , AdapterView.OnItemClickListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_center)
    TextView tvTitleCenter;
    @BindView(R.id.cbx_all_select)
    CheckBox cbCheckAll;
    @BindView(R.id.iv_report_delete)
    ImageView ivDelete;
    @BindView(R.id.lv_report_measure_list)
    ListView lvListMeasure;
    @BindView(R.id.blank_page_show_tv)
    TextView tvNoMeasureData;
    @BindView(R.id.btn_page_first)
    Button btnFirstPage;
    @BindView(R.id.btn_page_pre)
    Button btnPrePage;
    @BindView(R.id.btn_page_number)
    TextView tvShowNum;
    @BindView(R.id.btn_page_next)
    Button btnNextPage;
    @BindView(R.id.btn_page_last)
    Button btnLastPage;
    @BindView(R.id.tv_report_num)
    TextView tvHadChooseNum;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    private MeasureReportListAdapter adapter;
    private int reportTotalNum; //报告总条数
    private int reportHadChooseNum; //报告已选条数
    private List<MeasureDataBean> currentShowData; //页面当前显示数据列表
    private PatientBean currentPatient; //顶部栏显示的当前用户，切换用户不切换当前用户，只更换显示
    private int currentPage = 1; //当前页数，默认为第一页
    private String condition = ""; //查询条件
    private int allPage; //总共多少页
    private final int pageNum = 6; //每页固定查询数量
    private List<MeasureDataBean> selectNeedDeleteList = new ArrayList<>(); //需要删除的数据集合
    private boolean isCheckAll = false; //是否全选状态
    private boolean isHandSelectAllFlag = true; //标识手动操作全选按钮下走回调
    private PopupDialog popupDialog;
    private LoadingDialog loadingDialog;
    private ListPopupWindow listPopupWindow; //popWindow对象
    private long patientTotalNum; //用户总数量
    //限制popwindow高度的item数量
    private final int limitHeightNum = 4;
    private final int popHeight = 460;  //popWindow高度
    private String personAllStr; //姓名+性别+类型的组合字符串
    public static final String MEASURE_UUID = "measure_uuid"; //页面跳转UUID传值key
    private boolean isDeleteData = false; //记录标识是否有删除记录

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report_list);
        ButterKnife.bind(this);
        initView();
        initData();
        initEvent();
        initReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        patientTotalNum = DBDataUtil.getPatients(this);
        BroadcastUtils.sendHideForStartManage();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        currentPatient = UiUtils.getCurrent();
        tvTitle.setText(R.string.physical_examination_report);
        tvTitleCenter.setVisibility(View.VISIBLE);
        adapter = new MeasureReportListAdapter(this, currentShowData);
        lvListMeasure.setAdapter(adapter);
        adapter.setValue(true);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        showData();
        reslovePageData();
        personAllStr = presenter.getAllStr(currentPatient); //包括用户姓名、性别、用户类型
        setTitleText(personAllStr, getResources().getDrawable(R.mipmap.ic_nav_drop_down));
        tvHadChooseNum.setText(getString(R.string.report_choose_num, reportTotalNum
                , reportHadChooseNum));
        if (allPage >= 1) {
            tvShowNum.setText(currentPage + "/" + allPage);
        } else {
            tvShowNum.setText("0");
        }
        if (allPage >= 2) {
            //总页数大于等于2
            btnNextPage.setEnabled(true);
            btnLastPage.setEnabled(true);
        } else {
            btnNextPage.setEnabled(false);
            btnLastPage.setEnabled(false);
        }
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        ivBack.setOnClickListener(this);
        tvTitleCenter.setOnClickListener(this);
        btnFirstPage.setOnClickListener(this);
        btnPrePage.setOnClickListener(this);
        tvShowNum.setOnClickListener(this);
        btnNextPage.setOnClickListener(this);
        btnLastPage.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        cbCheckAll.setOnCheckedChangeListener(this);
        lvListMeasure.setOnItemClickListener(this);
    }

    /**
     * 注册广播
     */
    private void initReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastUtils.HEALRH_MEASURE_CARD_READER);
        intentFilter.addAction(BroadcastUtils.REFRESH_MEASURE_LIST);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public ReportListPresenterImpl initPresenter() {
        return new ReportListPresenterImpl();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.iv_back:
                //返回按钮
                finish();
                break;
            case R.id.tv_title_center:
                //下拉弹窗显示所有用户
                tvTitleCenter.setBackgroundResource(R.color.title_text_pressed);
                //Y轴偏移量
                int offY = (rlRoot.getHeight() - tvTitleCenter.getHeight()) / 2;
                //标题点击弹出下拉框显示本地所有用户
                if (listPopupWindow == null) {
                    if (patientTotalNum > limitHeightNum) {
                        listPopupWindow = new ListPopupWindow(ReportListActivity.this
                                , popHeight, tvTitleCenter.getWidth());
                    } else {
                        listPopupWindow = new ListPopupWindow(ReportListActivity.this
                                , ViewGroup.LayoutParams.WRAP_CONTENT, tvTitleCenter.getWidth());
                    }
                }
                listPopupWindow.showAsDropDown(tvTitleCenter, 0, offY);
                listPopupWindow.clearSeachBox();
                if (onDismissListener != null) {
                    listPopupWindow.setOnDismissListener(onDismissListener);
                }
                if (listener != null) {
                    listPopupWindow.setListener(listener);
                }
                break;
            case R.id.btn_page_first:
                //首页
                currentPage = 1;
                btnFirstPage.setEnabled(false);
                btnPrePage.setEnabled(false);
                btnNextPage.setEnabled(true);
                btnLastPage.setEnabled(true);
                adapter.setValue(true);
                //查询首页数据并显示
                showData();
                break;
            case R.id.btn_page_pre:
                //上一页
                if (currentPage - 1 < 1) {
                    return;
                }
                currentPage --;
                if (currentPage <= 1) {
                    btnFirstPage.setEnabled(false);
                    btnPrePage.setEnabled(false);
                } else {
                    btnFirstPage.setEnabled(true);
                    btnPrePage.setEnabled(true);
                }
                btnLastPage.setEnabled(true);
                btnNextPage.setEnabled(true);
                adapter.setValue(true);
                //查询当前页数数据并显示
                showData();
                break;
            case R.id.btn_page_number:
                //当前页数
                //点击页数弹窗
                ArrayList<String> datas = new ArrayList<>();
                for (int i = 1; i <= allPage; i++) {
                    if (i < 10) {
                        datas.add("0" + i);
                    } else {
                        datas.add(i + "");
                    }
                }
                initPopWindow(datas, view);
                break;
            case R.id.btn_page_next:
                //下一页
                if (currentPage + 1 > allPage) {
                    return;
                }
                currentPage ++;
                if (currentPage >= allPage) {

                    btnLastPage.setEnabled(false);
                    btnNextPage.setEnabled(false);
                } else {
                    btnLastPage.setEnabled(true);
                    btnNextPage.setEnabled(true);
                }
                btnFirstPage.setEnabled(true);
                btnPrePage.setEnabled(true);
                adapter.setValue(true);
                //查询当前页数并显示
                showData();
                break;
            case R.id.btn_page_last:
                //尾页
                btnFirstPage.setEnabled(true);
                btnPrePage.setEnabled(true);
                btnNextPage.setEnabled(false);
                btnLastPage.setEnabled(false);
                //如果网络没链接或者没有数据
                if (allPage == 0) {
                    tvShowNum.setText("1");
                    btnFirstPage.setEnabled(false);
                } else {
                    currentPage = allPage;
                    if (currentPage <= 1) {
                        btnFirstPage.setEnabled(false);
                        btnPrePage.setEnabled(false);
                    } else {
                        btnFirstPage.setEnabled(true);
                        btnPrePage.setEnabled(true);
                    }
                }
                adapter.setValue(true);
                //查询当前页数并显示
                showData();
                break;
            case R.id.iv_report_delete:
                if (selectNeedDeleteList != null && selectNeedDeleteList.size() > 0) {
                    popupDialog = new PopupDialog(this,
                            UiUtils.getString(R.string.delete_data),
                            new PopupDialog.UpdateButtonState() {

                                @Override
                                public void getButton(Boolean pressed) {

                                    popupDialog.dismiss();
                                    if (pressed) {
                                        showLoadingDialog(UiUtils.getString(R.string.deleting));
                                        presenter.deleteSelectMeasures(selectNeedDeleteList);
                                    }
                                }

                                @Override
                                public void close() {
                                    popupDialog.dismiss();
                                }
                            });
                    popupDialog.show();
                    popupDialog.setContent(UiUtils.getString(R.string.delete_data_notice));
                } else {
                    ToastUtils.showShortToast(R.string.please_select_data);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 窗体消失监听
     */
    private PopupWindow.OnDismissListener onDismissListener =
            new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    tvTitleCenter.setBackgroundResource(0);
                }
            };

    /**
     * 点击item选中监听
     */
    private ListPopupWindow.OnPopwindowItemClickDismissListener listener =
            new ListPopupWindow.OnPopwindowItemClickDismissListener() {
                @Override
                public void onItemClickDismiss(int position, List<PatientBean> list) {
                    currentPatient = list.get(position);
                    reportHadChooseNum = 0;
                    currentPage = 1;
                    initData();
                    selectNeedDeleteList.clear();
                    cbCheckAll.setChecked(false);
                }
            };

    /**
     * 从云南1.0.1合并过来的选择页面
     *
     * @param name 姓名集合
     * @param view 视图
     */
    private void initPopWindow(ArrayList<String> name, View view) {

        View contentView = LayoutInflater.from(this.getApplicationContext())
                .inflate(R.layout.popupwindow_page, null);

        final PopupWindow popupWindow = new PopupWindow(1300, 350);
        popupWindow.setContentView(contentView);

        TextView textView = (TextView) contentView.findViewById(R.id.pop_title);
        textView.setText(UiUtils.getString(R.string.select_page_number));
        ListView listView = (ListView) contentView.findViewById(R.id.pop_list);
        PopupWindowAdapter popAdapter = new PopupWindowAdapter(this, name);
        listView.setAdapter(popAdapter);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAsDropDown(view);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String strPageNumber = (i + 1) + "";
                if (strPageNumber == null || strPageNumber.equals("0")) {
                    //当前页默认1
                    currentPage = 1;
                    tvShowNum.setText(currentPage + "");
                } else {
                    //选择当前页
                    currentPage = Integer.valueOf(strPageNumber);
                    tvShowNum.setText(strPageNumber + "/" + allPage);
                }
                if (currentPage <= 1) {
                    //首页
                    btnFirstPage.setEnabled(false);
                    btnPrePage.setEnabled(false);
                    btnNextPage.setEnabled(true);
                    btnLastPage.setEnabled(true);
                } else if (currentPage >= allPage) {
                    //末页
                    btnFirstPage.setEnabled(true);
                    btnPrePage.setEnabled(true);
                    btnNextPage.setEnabled(false);
                    btnLastPage.setEnabled(false);
                } else {
                    btnFirstPage.setEnabled(true);
                    btnPrePage.setEnabled(true);
                    btnNextPage.setEnabled(true);
                    btnLastPage.setEnabled(true);
                }
                if (allPage == 1) {
                    tvShowNum.setEnabled(true);
                    btnFirstPage.setEnabled(false);
                    btnPrePage.setEnabled(false);
                    btnNextPage.setEnabled(false);
                    btnLastPage.setEnabled(false);
                }
                adapter.setValue(true);
                showData();
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 显示进度条
     * @param content 进度条内容
     */
    private void showLoadingDialog(String content) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this, "");
            loadingDialog.setOnKeyListener(keyListener);
        }
        loadingDialog.show();
        loadingDialog.setContent(content);
    }

    DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == 4) { //f1
                if (loadingDialog.isShowing()) {
                    return true;
                }
                UiUtils.hideProgress();
            }
            return false;
        }
    };

    /**
     * 设置标题栏
     * @param title 文字
     * @param drawable 图标
     */
    private void setTitleText(String title, Drawable drawable) {
        if (tvTitleCenter != null && !TextUtils.isEmpty(title)) {
            tvTitleCenter.setText(title);
            if (drawable != null) {
                drawable.setBounds(0, 0, drawable.getMinimumWidth()
                        , drawable.getMinimumHeight());
                tvTitleCenter.setCompoundDrawables(null, null, drawable
                        , null);
            }
        }
    }

    /**
     * 数据刷新显示
     */
    private void showData() {
        currentShowData = presenter.getMeasureDataList(currentPatient.getIdcard()
                , (currentPage - 1) * pageNum);
        adapter.setDatas(currentShowData);
        tvShowNum.setText(currentPage + "/" + allPage);
    }

    /**
     * 计算页面数据，总共多少页数据
     */
    private void reslovePageData() {
        reportTotalNum = (int) presenter.getMeasures(currentPatient.getIdcard());
        if (reportTotalNum % pageNum > 0) {
            //有余数，则加1
            allPage = reportTotalNum / pageNum + 1;
        } else {
            allPage = reportTotalNum / pageNum;
        }
    }

    /**
     * 不同勾选状况下的页面显示
     * @param measureDataBean 操作的测量数据
     * @param isChecked 是否选中
     */
    public void showViewData(MeasureDataBean measureDataBean, boolean isChecked) {
        isHandSelectAllFlag = false;
        isCheckAll = false;
        adapter.setCheckAll(isCheckAll);
        cbCheckAll.setChecked(isCheckAll);
        changeMeasureDataBeanByUuid(selectNeedDeleteList, measureDataBean, !isChecked);
        showHadChooseValue(selectNeedDeleteList.size());
        isHandSelectAllFlag = true;
    }

    /**
     * 获取选择数据集合
     * @return 选择的数据列表集合
     */
    public List<MeasureDataBean> getSelectNeedDeleteList() {
        return selectNeedDeleteList;
    }

    /**
     * 根据UUID判断，1.移除时，相同UUID的数据去除掉，2.增加时相同UUID不增加
     * @param sourceList 源数据
     * @param measureDataBean 用户数据
     * @param isRemove true 移除数据 false 添加数据
     */
    private void changeMeasureDataBeanByUuid(List<MeasureDataBean> sourceList
            , MeasureDataBean measureDataBean, boolean isRemove) {
        //集合中间变量，用于存储需删除数据集合
        List<MeasureDataBean> tempList = new ArrayList<>();
        if (isRemove) {
            if (sourceList != null && sourceList.size() > 0) {
                for (MeasureDataBean measureDataBean1 : sourceList) {
                    if (measureDataBean1.getUuid().equals(measureDataBean.getUuid())) {
                        tempList.add(measureDataBean1);
                    }
                }
                sourceList.removeAll(tempList);
            }
        } else {
            List<String> uuidList = new ArrayList<>();
            for (MeasureDataBean measureDataBean1 : sourceList) {
                uuidList.add(measureDataBean1.getUuid());
            }
            if (!uuidList.contains(measureDataBean.getUuid())) {
                sourceList.add(measureDataBean);
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if (!isHandSelectAllFlag) {
            isHandSelectAllFlag = true;
        } else {
            isCheckAll = isChecked;
            adapter.setCheckAll(isCheckAll);
            if (isCheckAll) {
                //全选选中
                showHadChooseValue(reportTotalNum);
                selectNeedDeleteList.clear();
                selectNeedDeleteList.addAll(presenter
                        .getAllMeasure(currentPatient.getIdcard()));
            } else {
                //全选取消
                showHadChooseValue(0);
                selectNeedDeleteList.clear();
            }
        }
        Log.e("xsc_isHandSelectAllFlag", "" + isHandSelectAllFlag);
    }

    /**
     * 显示已选多少条记录数值
     * @param num 数值
     */
    public void showHadChooseValue(int num) {
        reportHadChooseNum = num;
        tvHadChooseNum.setText(getString(R.string.report_choose_num, reportTotalNum
                , reportHadChooseNum));
    }

    /**
     * 获取体检报告列表页面的当前查看用户
     * @return 列表页面的当前用户(不是软件的当前用户)
     */
    public PatientBean getCurrentPatient() {
        return currentPatient;
    }

    @Override
    public void refreshView() {
        isDeleteData = true;
        dismissLoadingDialog();
        currentPage = 1;
        showData();
        reslovePageData();
        reportHadChooseNum = 0;
        tvHadChooseNum.setText(getString(R.string.report_choose_num, reportTotalNum
                , reportHadChooseNum));
        if (allPage == 1) {
            tvShowNum.setText(currentPage + "/" + allPage);
            tvShowNum.setEnabled(true);
            btnFirstPage.setEnabled(false);
            btnPrePage.setEnabled(false);
            btnNextPage.setEnabled(false);
            btnLastPage.setEnabled(false);
        } else if (allPage > 1) {
            tvShowNum.setText(currentPage + "/" + allPage);
            tvShowNum.setEnabled(true);
            btnFirstPage.setEnabled(false);
            btnPrePage.setEnabled(false);
            btnNextPage.setEnabled(true);
            btnLastPage.setEnabled(true);
        } else {
            tvShowNum.setText("0");
            tvShowNum.setEnabled(false);
            cbCheckAll.setChecked(false);
            btnFirstPage.setEnabled(false);
            btnPrePage.setEnabled(false);
            btnNextPage.setEnabled(false);
            btnLastPage.setEnabled(false);
        }
        selectNeedDeleteList.clear();
    }

    /**
     * 关闭进度条
     */
    private void dismissLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BroadcastUtils.HEALRH_MEASURE_CARD_READER:
                    //接受到刷身份证后的广播
                    String idcard = intent.getStringExtra(IDCARD); //读取到的身份证号
                    if (listPopupWindow != null && listPopupWindow.isShowing()) {
                        listPopupWindow.setEtData(idcard);
                    } else {
                        //查询出来的用户
                        PatientBean tempPatientBean = presenter.getPatientBean(idcard);
                        if (tempPatientBean != null) {
                            currentPatient = tempPatientBean;
                            reportHadChooseNum = 0;
                            currentPage = 1;
                            initData();
                        } else {
                            //身份证查询本地无该用户时候进行相应提醒
                            ToastUtils.showShortToast(R.string.patient_no_exits);
                        }
                    }
                    break;
                case BroadcastUtils.REFRESH_MEASURE_LIST:
                    //刷新当前页数据
                    adapter.setValue(true);
                    //查询当前页数并显示
                    showData();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
        UiUtils.setMeasureDataBeen(null);
        if (isDeleteData) {
            sendBroadcast(new Intent(BroadcastUtils.REFRESH_NEW_DATA));
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Intent intent = new Intent(this, HealthReportActivity.class);
        intent.putExtra(MEASURE_UUID, currentShowData.get(position).getUuid());
        startActivity(intent);
    }
}
